﻿using System;

namespace ControleRepresentante.Migration
{
    class MigrationStatus
    {
        private readonly Migrator m_Migrator;
        private DateTime? m_LastSetCurrentProgressTime;

        public string CurrentStep { get; set; }
        public int CurrentIndex { get; private set; }
        public int Total { get; private set; }
        public double CurrentStepProgress { get; set; }
        public TimeSpan EstimatedTime { get; set; }

        public MigrationStatus(Migrator migrator)
        {
            m_Migrator = migrator;
        }

        public void SetCurrentProgress(int index, int total)
        {
            if (m_Migrator.IsCancel)
            {
                CurrentStep = "Canceled";
                m_Migrator.FireEnd();
                m_Migrator.MigrationThread.Abort();
            }

            CurrentIndex = index;
            Total = total;
            double oldProgress = CurrentStepProgress;
            DateTime currentTime = DateTime.Now;
            CurrentStepProgress = 100 * Convert.ToDouble(index) / Convert.ToDouble(total);

            if (m_LastSetCurrentProgressTime.HasValue)
            {
                EstimatedTime =
                    TimeSpan.FromMilliseconds(currentTime.Subtract(m_LastSetCurrentProgressTime.Value).TotalMilliseconds *
                                              (100 - CurrentStepProgress) / (CurrentStepProgress - oldProgress));
            }

            m_LastSetCurrentProgressTime = currentTime;
        }
    }
}